#!/usr/bin/python
# -*- coding: utf-8 -*- 

import constante as cons
import curses
import curses.wrapper
import chip8
import time


class CursesEngine(chip8.TemplateGraphicEngine):
	def __init__(self, scr):
		self.keyboard = (ord("o"), ord("w"), ord("x"), ord("c"), ord("q"), ord("s"), ord("d"), ord("a"), ord("z"), ord("e"), ord("i"), ord("p"), ord("k"), ord("l"), ord("m"))
		self.prekey = None
		self.initialize_windows(scr)
		chip8.TemplateGraphicEngine.__init__(self)
		self.draw(	clear= self.outscr.erase,
					refresh= self.outscr.refresh,
					draw_BLACK= lambda x,y: self.outscr.addch(y,x,' '),
					draw_WHITE= lambda x,y: self.outscr.addch(y,x,'@'),
					bind_key= self.bind_input)
	
	def bind_input(self):
		ch = self.stdscr.getch()
		if self.prekey != None and ch != self.prekey:
			self.bus_input[self.prekey] = 0
			self.prekey = None
		if ch == ord('n'):
			cons.IS_RUNNING = False
		elif ch in self.keyboard:
			ind = self.keyboard.index(ch)
			self.bus_input[ind] = 1
			self.prekey = ind
	
	def initialize_windows(self, scr):
		curses.use_default_colors()
		curses.noecho()
		curses.curs_set(0)
		
		self.stdscr = scr
		self.stdscr.addstr("Chip V8 Emulation")
		self.stdscr.nodelay(1)
		self.outscr = self.stdscr.subwin(cons.SCR_HEIGHT+1,cons.SCR_WIDTH+1,1,0)
		self.outscr.border(0)
		self.stdscr.refresh()


if __name__ == '__main__':
	import sys
	cons.ROM = sys.argv[1]
	curses.wrapper(CursesEngine)
	curses.endwin()
